﻿using System;
using ELearning.BLL;
using ELearning.Common.Extensions;
using ELearning.Common.Model;
using ELearning.Models;
using ELearning.Models.ViewModel.Org;
using System.Linq;
using System.Web.Http;
using ELearning.Models.ViewModel.User;
using System.Linq.Expressions;
using ELearning.Common.CommonStr;

namespace ELearning.API.Controllers.AdminControllers
{
    /// <summary>
    /// 组织信息控制器
    /// </summary>
    public class OrgController : BaseApiController
    {
        /// <summary>
        /// 组织服务
        /// </summary>
        protected EOrgService orgService = new EOrgService();
        /// <summary>
        /// 用户服务
        /// </summary>
        protected ESysUserService userService = new ESysUserService();

        /// <summary>
        /// 获取组织机构列表
        /// </summary>
        [HttpPost, Route("api/Org/GetOrgList")]
        public ServiceResponse<OrgViewModel> GetRegesterList(GetOrgRequest request)
        {
            var viewModel = new OrgViewModel();
            var orgPage = orgService.GetOrgList(request);
            if (orgPage != null)
            {
                viewModel.TotalCount = orgPage.TotalItems.ObjToInt();
                foreach (var log in orgPage.Items)
                {
                    viewModel.OrgItems.Add(log);
                }
            }
            return ServiceResponse<OrgViewModel>.SuccessResponse("success", viewModel);
        }

        /// <summary>
        /// 获取所有组织结构信息
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("api/Org/GetAllOrgList")]
        public ServiceResponse<OrgViewModel> GetAllOrgList()
        {
            Expression<Func<EOrg, bool>> whereLamdba = (u) => u.IsDelete == false;
            var viewModel = new OrgViewModel();
            var orgPage = orgService.FindList(whereLamdba, "CreateTime", true);
            if (orgPage != null)
            {
                viewModel.TotalCount = orgPage.ObjToInt();
                foreach (var log in orgPage)
                {
                    viewModel.OrgItems.Add(log);
                }
            }
            return ServiceResponse<OrgViewModel>.SuccessResponse("success", viewModel);
        }

        /// <summary>
        /// 获取父级组织下拉框列表
        /// </summary>
        [HttpGet, Route("api/Org/GetParentOptionItemOrgList")]
        public ServiceResponse<OrgViewModel> GetParentOptionItemOrgList()
        {
            Expression<Func<EOrg, bool>> whereLamdba = (u) => u.IsDelete == false && string.IsNullOrEmpty(u.parent_code);
            var viewModel = new OrgViewModel();
            var orgPage = orgService.FindList(whereLamdba, "CreateTime", true);
            if (orgPage != null)
            {
                viewModel.TotalCount = orgPage.ObjToInt();
                foreach (var log in orgPage)
                {
                    viewModel.OrgItems.Add(log);
                }
            }
            return ServiceResponse<OrgViewModel>.SuccessResponse(CommonConst.OprateSuccessStr, viewModel);
        }

        /// <summary>
        /// 获取子级组织下拉框列表
        /// </summary>
        [HttpGet, Route("api/Org/GetSubOptionItemOrgList")]
        public ServiceResponse<OrgViewModel> GetSubOptionItemOrgList()
        {
            var parentCode = CurrentUserModel.OrgCode;
            if (string.IsNullOrEmpty(parentCode))
                parentCode = CommonConst.DEFAULT_ORGCODE;
            var org = orgService.Find(o => o.org_code == parentCode);
            if (!string.IsNullOrEmpty(org.parent_code))
            {
                parentCode = org.parent_code;
                org = orgService.Find(o => o.org_code == parentCode);
            }
            Expression<Func<EOrg, bool>> whereLamdba = (u) => u.IsDelete == false && u.parent_code == parentCode;
            var viewModel = new OrgViewModel();

            viewModel.OrgItems.Add(org);
            var orgPage = orgService.FindList(whereLamdba, "CreateTime", true).ToList();
            if (orgPage.Any())
            {
                viewModel.TotalCount = orgPage.ObjToInt();
                foreach (var log in orgPage)
                {
                    viewModel.OrgItems.Add(log);
                }
            }
            return ServiceResponse<OrgViewModel>.SuccessResponse("success", viewModel);
        }

        /// <summary>
        /// 添加
        /// </summary>
        [HttpPost, Route("api/Org/AddOrg")]
        public ServiceResponse<EOrg> AddOrg(EOrg o)
        {
            var r1 = orgService.Find(u => !u.IsDelete && u.org_code == o.org_code);
            if (r1.IsNotNull())
                return ServiceResponse<EOrg>.SuccessResponse(CommonConst.ORGCODE_REPEAT, o, CommonConst.ORGCODE_REPEAT_CODE);
            var org = new EOrg
            {
                org_id = Guid.NewGuid(),
                org_code = o.org_code,
                Creater = CurrentUserModel.LoginName,
                CreateTime = DateTime.Now,
                org_name = o.org_name,
                org_type = o.org_type,
                parent_code = o.parent_code,
                owner_call = o.owner_call,
                owner_phone = o.owner_phone,
                org_adress = o.org_adress,
                AccountLimit = o.AccountLimit,
                org_owner = o.org_owner,
                org_remark = o.org_remark,
                IsDelete = false,
                ModifyTime = DateTime.Now,
                InviteCode = o.org_code
            };
            orgService.Add(org);

            return ServiceResponse<EOrg>.SuccessResponse("操作成功", o);
        }

        /// <summary>
        /// 更新
        /// </summary>
        [HttpPost, Route("api/Org/UpdateOrg")]
        public ServiceResponse<EOrg> UpdateOrg(EOrg o)
        {
            var r1 = orgService.Find(u => !u.IsDelete && u.org_id != o.org_id && u.org_code == o.org_code);
            if (r1.IsNotNull())
                return ServiceResponse<EOrg>.SuccessResponse(CommonConst.ORGCODE_REPEAT, o, CommonConst.ORGCODE_REPEAT_CODE);
            var org = orgService.Find(r => !r.IsDelete && r.org_id == o.org_id);
            //org.org_code = o.org_code;
            org.Modifyer = CurrentUserModel.LoginName;
            org.ModifyTime = DateTime.Now;
            org.org_name = o.org_name;
            org.AccountLimit = o.AccountLimit;
            org.org_type = o.org_type;
            org.org_owner = o.org_owner;
            org.owner_call = o.owner_call;
            org.owner_phone = o.owner_phone;
            orgService.Update(org);
            return ServiceResponse<EOrg>.SuccessResponse("操作成功", o);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">角色id</param>
        [HttpPost, Route("api/Org/DeleteOrg")]
        public ServiceResponse<int> DeleteOrg(Guid id)
        {
            var role = orgService.Find(r => !r.IsDelete && r.org_id == id);
            role.IsDelete = true;
            orgService.Update(role);
            return ServiceResponse<int>.SuccessResponse("操作成功", 1);
        }

        /// <summary>
        /// 用户名是否存在
        /// </summary>
        [HttpGet, Route("api/Org/isExistOrgCode")]
        public ServiceResponse<bool> IsExistOrgCode(Guid id, string org_code)
        {
            var org = orgService.Find(u => !u.IsDelete && u.org_id != id && u.org_code == org_code);
            var r = org == null;
            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, r);
        }

        /// <summary>
        /// 根据code获取组织成员列表
        /// </summary>
        /// <param name="org_code"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        [HttpGet, Route("api/Org/getUserListByOrgCode")]
        public ServiceResponse<GetUserViewModel> getUserListByOrgCode(string org_code, string username)
        {
            var viewModel = new GetUserViewModel();
            var userPage = userService.GetUserListByOrgCode(org_code, username);
            if (userPage != null)
            {
                viewModel.TotalCount = userPage.TotalItems.ObjToInt();
                foreach (var user in userPage.Items)
                {
                    var u = new GetUserItem
                    {
                        UserId = user.UserID,
                        AccountStatus = user.AccountStatus,
                        Birthday = user.Birthday,
                        CreateTime = user.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                        Company = user.Company,
                        Creater = user.Creater,
                        Department = user.Department,
                        Email = user.Email,
                        HeadPhoto = user.HeadPhoto,
                        LoginName = user.LoginName,
                        ModifyTime = user.ModifyTime,
                        MobilePhone = user.MobilePhone,
                        Position = user.Position,
                        Remark = user.Remark,
                        UserName = user.UserName,
                        UserType = user.UserType,
                        OfficeTel = user.OfficeTel,
                        Password = user.Password,
                        ConfirmPassword = user.Password,
                        Sex = getSex(user.Sex)
                    };
                    viewModel.UserItems.Add(u);
                }
            }
            return ServiceResponse<GetUserViewModel>.SuccessResponse("success", viewModel);
        }

        /// <summary>
        /// 获取性别字符串 
        /// </summary>
        private string getSex(int sex)
        {
            var str = string.Empty;
            switch (sex)
            {
                case 1:
                    str = "保密";
                    break;
                case 2:
                    str = "男";
                    break;
                case 3:
                    str = "女";
                    break;
                default:
                    str = "";
                    break;
            }
            return str;
        }
    }
}